package carpediem.xin.tamplate.network;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * Created by zhaijianwei on 17/1/5.
 */

public class ProgressRequestBody extends RequestBody {

    private static final long SEGMENT_SIZE = 2048; //package path: okio.Segment.SIZE
    private RequestBody mRequestBody;
    private ProgressListener mProgressListener;
    private BufferedSink bufferedSink;
    private File file;
    private long bytesTotal = 0;

    public ProgressRequestBody(MediaType mediaType, File file, ProgressListener listener) {
        if (null == mediaType) throw new NullPointerException("mediaType is null.");
        if (null == file) throw new NullPointerException("file is null.");
        this.file = file;
        this.mRequestBody = RequestBody.create(mediaType, file);
        this.mProgressListener = listener;
    }

    //返回了requestBody的类型，想什么form-data/MP3/MP4/png等等等格式
    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    //返回了本RequestBody的长度，也就是上传的totalLength
    @Override
    public long contentLength() throws IOException {
        return mRequestBody.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        if (0 == bytesTotal) bytesTotal = contentLength();
        try {
            source = Okio.source(file);
            long bytesWritten = 0;
            long bytesBuffer;
            while ((bytesBuffer = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                bytesWritten += bytesBuffer;
                sink.flush();
                this.mProgressListener.onProgress(bytesWritten, bytesTotal, bytesWritten == bytesTotal);
            }
        } finally {
            Util.closeQuietly(source);
        }
    }

}
